/**
 * Created by zoushuiyun
 */
import {OnInit, Injectable} from '@angular/core';

/**
 * 缓存服务  将ajax请求的一些状态数据存储到localStorage中，避免系统中频繁请求提升用户体验
 */
@Injectable()
export class CacheService implements OnInit {


  static USER_TOKEN_KEY = 'USER_TOKEN';
  static FIRST_URL = 'FIRST_URL';
  static CURR_USER_KEY = 'USER';
  static CURR_USER_INFO_KEY = 'USER_INFO';


  ngOnInit(): void {
    if (typeof window.localStorage === 'undefined') {
      alert('请使用chrome或更高版本的IE浏览器');
    }
  }

  private add(key, obj) {
    if (obj) {
      if (typeof obj === 'object') {
        // storage中只能存储字符串，所以将json对象转换成字符串
        const objStr = JSON.stringify(obj);
        window.localStorage.setItem(key, objStr);
      } else {
        window.localStorage.setItem(key, obj);
      }
    }
  }

  private get(key) {
    const objStr = window.localStorage.getItem(key);
    if (objStr) {
      try {
        // 重新转换为对象
        return JSON.parse(objStr);
      } catch (err) {

      }
    }
    return objStr;
  }

  clear() {
    window.localStorage.removeItem(CacheService.USER_TOKEN_KEY);
    window.localStorage.removeItem(CacheService.FIRST_URL);
    window.localStorage.removeItem(CacheService.CURR_USER_KEY);
    window.localStorage.removeItem(CacheService.CURR_USER_INFO_KEY);

  }

  /**
   * token信息
   * @param currUser
   */
  setTokenInfo(token: any) {
    this.add(CacheService.USER_TOKEN_KEY, token);
  }

  /**
   *  token信息
   * @returns {any|any}
   */
  getTokenInfo(): any {
    return this.get(CacheService.USER_TOKEN_KEY);
  }

  /**
   * 请求的url
   * @param currUser
   */
  setFirstUrl(url: any) {
    this.add(CacheService.FIRST_URL, url);
  }

  /**
   * 请求的url
   * @returns {any|any}
   */
  getFirstUrl(): any {
    return this.get(CacheService.FIRST_URL);
  }

  /**
   * 缓存用户数据详细数据
   * @param currUser
   */
  setCurrUserInfo(currUserInfo: any) {
    this.add(CacheService.CURR_USER_INFO_KEY, currUserInfo);
  }

  /**
   * 获取用户数据 详细数据
   * @returns {any|any}
   */
  getCurrUserInfo(): any {
    return this.get(CacheService.CURR_USER_INFO_KEY);
  }


  /**
   * 缓存用户数据 对应currUserService中对象
   * @param currUser
   */
  setCurrUser(currUser: any) {
    this.add(CacheService.CURR_USER_KEY, currUser);
  }

  /**
   * 获取用户数据 对应currUserService中对象
   * @returns {any|any}
   */
  getCurrUser(): any {
    return this.get(CacheService.CURR_USER_KEY);
  }


}
